package com.zhny.util;

/**
 * 
 * @author Alex
 * @date 2017年11月10日 下午4:04:43
 */
public class BytesUtils {
	public static byte[] getBytes(int x) {
		byte[] bytes = new byte[4];
		byte b;
		for (int i = 0; i < 4; i++) {
			b = (byte) (x & 0xff);
			bytes[i] = b;
			x >>= 8;
		}
		return bytes;
	}

	public static byte[] getBytes(short x) {
		byte[] bytes = new byte[2];
		byte b;
		for (int i = 0; i < 2; i++) {
			b = (byte) (x & 0xff);
			bytes[i] = b;
			x >>= 8;
		}
		return bytes;
	}

	public static byte[] getBytes(char[] c) {
		byte[] bytes = new byte[c.length];
		for (int i = 0; i < c.length; i++)
			bytes[i] = (byte) c[i];
		return bytes;
	}

	public static byte[] getBytes(String s) {
		char[] c = s.toCharArray();
		return getBytes(c);
	}

	public static int toInt(byte[] bytes) {
		return (int) ((((bytes[3] & 0xff) << 24) | ((bytes[2] & 0xff) << 16) | ((bytes[1] & 0xff) << 8)
				| ((bytes[0] & 0xff) << 0)));

	}

	public static short toShort(byte[] bytes) {
		return (short) (((bytes[1] << 8) | bytes[0] & 0xff));
	}

	public static long toLong(byte[] bytes) {
		return Integer.toUnsignedLong(toInt(bytes));
	}


}
